﻿
@{
    int pageSize = ViewBag.PageSize;
    int pageIndex = ViewBag.PageIndex;
    long totalRecords = ViewBag.TotalRecords;
    string action = ViewBag.Action;
}


@if (pageIndex != 0)
{ 
    @Html.ActionLink(" 首页  ", action, new { PageIndex = 0, PageSize = pageSize })
}
else
{
    @Html.Raw(" 首页 ") ;
}

@if(pageIndex > 0){
    @Html.ActionLink(" 上一页  ", action, new { PageIndex = pageIndex - 1, PageSize = pageSize })
}
else
{
    @Html.Raw(" 上一页  ");
}

@{
    string etc = " ... ";
    int halfwindow = 5; //总连接数的一半
    long rightadd = 0;//右侧应该添上的链接数
    long leftadd = 0;//左侧应该添上的链接数
    long first = 0;
    long totalPages = totalRecords % pageSize == 0 ? totalRecords / pageSize : totalRecords / pageSize + 1;
    long last = totalPages;
    
    int temp = pageIndex - halfwindow;
    
    if (temp > 0)
    {
        first = temp;
    }
    else
    {
        rightadd = -temp; 
    }

    
    temp = pageIndex + halfwindow;

    if (temp < totalPages)
    {
        last = temp; 
    }
    else
    {
        leftadd = halfwindow - (totalPages - pageIndex);
    }

    if (leftadd > 0)
    {
        first = first > leftadd ? first - leftadd : 0;
    }

    if (rightadd > 0)
    {
        last = (totalPages - last) > rightadd ? last + rightadd : totalPages;
    }
    
    if (first > 0 && last - first == halfwindow * 2)
    {
        @etc 
    }


    //打印从第一页到最后一页的链接
    for (long k = first; k < last; k++)
    {
        if (k != pageIndex)
        { 
            @Html.ActionLink(k.ToString() + " ", action, new { PageIndex = k, PageSize = pageSize });
        }
        else
        {
            @Html.Raw(k.ToString()) 
        }
    }


    if (last < totalPages && last - first == halfwindow * 2)
    {
        @etc 
    }
    
}
@if (pageIndex < totalPages - 1)
{
    @Html.ActionLink(" 下一页 ", action, new { PageIndex = pageIndex + 1, PageSize = pageSize })
}
else
{
    @Html.Raw(" 下一页 ");
}
@if (pageIndex != totalPages - 1)
{ 
    @Html.ActionLink(" 末页 ", action, new { PageIndex = totalPages - 1, PageSize = pageSize })
}
else
{
    @Html.Raw(" 末页 ");
}
共计 @totalPages 页 , @totalRecords 条记录
